/**
 * 
 */
package com.youth.fund.hk.hostManager.thymeleaf.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.youth.fund.hk.hostManager.manager.dao.HtmlMapperDao;
import com.youth.fund.hk.hostManager.manager.datamodel.HtmlMapperModel;
import com.youth.fund.hk.hostManager.thymeleaf.service.ThymeleafService;

/**
 * @author Sunk_Sky
 *
 *         2014年11月17日下午3:50:51
 */
@Service("ThymeleafService")
public class ThymeleafServiceImpl implements ThymeleafService
{
	@Autowired
	@Qualifier("templateEngine")
	private TemplateEngine engine;

	@Value("${thymeleaf.targetPath}")
	private String targetPath;

	@Value("${thymeleaf.targetFileType}")
	private String targetFileType;

	@Value("${thymeleaf.hostIp}")
	private String hostIp;

	@Value("${thymeleaf.urlSuffix}")
	private String urlSuffix;

	@Autowired
	@Qualifier("HtmlMapperDao")
	private HtmlMapperDao dao;

	@Override
	public String transferInformation(String keyword,
			Map<String, Object> dataMap, String pageId)
	{
		if (!engine.isInitialized())
		{
			engine.initialize();
		}
		String url = "";

		Context context = new Context();

		context.setVariables(dataMap);

		String targetFileName = this.getPath(keyword, pageId);

		String templatePath = this.getTemplatePath(keyword);

		if ("".equalsIgnoreCase(templatePath)
				|| "".equalsIgnoreCase(targetFileName))
		{
			return "";
		}
		String result = engine.process(this.getTemplatePath(keyword), context);

		File targetFile = new File(targetFileName);

		File dir = targetFile.getParentFile();

		if ((dir != null) && (!dir.exists()))
		{
			dir.mkdirs();
		}
		if (!targetFile.exists())
		{
			try
			{
				targetFile.createNewFile();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		try
		{
			OutputStreamWriter osWriter = new OutputStreamWriter(
					new FileOutputStream(targetFile), "UTF-8");

			BufferedWriter writer = new BufferedWriter(osWriter);

			writer.write(result);

			writer.flush();

			writer.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		url = this.getURL(keyword, pageId);

		return url;

	}

	@Override
	public String transferType(String keyword, Map<String, Object> dataMap)
	{
		if (!engine.isInitialized())
		{
			engine.initialize();
		}
		String url = "";

		Context context = new Context();

		context.setVariables(dataMap);

		String targetFileName = this.getPath(keyword, "");

		String templatePath = this.getTemplatePath(keyword);

		if ("".equalsIgnoreCase(templatePath)
				|| "".equalsIgnoreCase(targetFileName))
		{
			return "";
		}
		String result = engine.process(this.getTemplatePath(keyword), context);

		File targetFile = new File(targetFileName);

		File dir = targetFile.getParentFile();

		if ((dir != null) && (!dir.exists()))
		{
			dir.mkdirs();
		}
		if (!targetFile.exists())
		{
			try
			{
				targetFile.createNewFile();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		try
		{
			OutputStreamWriter osWriter = new OutputStreamWriter(
					new FileOutputStream(targetFile), "UTF-8");

			BufferedWriter writer = new BufferedWriter(osWriter);

			writer.write(result);

			writer.flush();

			writer.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		url = this.getURL(keyword, "");

		return url;

	}

	private String getPath(String keyword, String id)
	{
		String result = "";

		HtmlMapperModel condition = new HtmlMapperModel();

		condition.setKeyword(keyword);

		HtmlMapperModel model = dao.queryOne(condition);

		if (model != null && model.getTarget_path() != null)
		{
			if (id == null || "".equalsIgnoreCase(id))
			{
				result = this.targetPath + model.getTarget_path()
						+ this.targetFileType;
			} else
			{
				result = this.targetPath + model.getTarget_path() + id
						+ this.targetFileType;
			}
		}

		return result;
	}

	private String getTemplatePath(String keyword)
	{
		String result = "";

		HtmlMapperModel condition = new HtmlMapperModel();

		condition.setKeyword(keyword);

		HtmlMapperModel model = dao.queryOne(condition);

		if (model != null)
		{
			result = model.getSource_template();
		}

		return result;
	}

	private String getURL(String keyword, String id)
	{
//		this.hostIp = this.getIP();
		
		String result = "";

		HtmlMapperModel condition = new HtmlMapperModel();

		condition.setKeyword(keyword);

		HtmlMapperModel model = dao.queryOne(condition);

		if (model != null)
		{
			if (id == null || "".equalsIgnoreCase(id))
			{
				result = this.hostIp +model.getUrl() + this.urlSuffix;
			}
			result = this.hostIp + model.getUrl() + id + this.urlSuffix;
		}

		return result;
	}
	
	private String getIP()
	{
		String result = "";
		try
		{
			InetAddress netAddress = InetAddress.getLocalHost();

			result = netAddress.getHostAddress();

		} catch (UnknownHostException e)
		{
			
			e.printStackTrace();
		}

		return "http://"+result+"/";
	}
}
